//
//  ModuleFirstTravelsViewController.m
//  艾听歌
//
//  Created by dllo on 16/5/28.
//  Copyright © 2016年 dllo. All rights reserved.
//
#import "FirstTravelsController.h"
#import "TravelsFirst_FirstTableViewCell.h"

#import "TravelsDetailsController.h"
#import "ModuleFirstUserHomepageViewController.h"

#import "ModuleFirst_TravelsTitleModel.h"
#import "ModuleFirst_UserInformationModel.h"


#define ViewWidth  self.view.frame.size.width
#define ViewHeight self.view.frame.size.height

#define TabelViewW  self.travelsTableView.frame.size.width
#define TabelViewH  self.travelsTableView.frame.size.height

static NSString *const tableViewCell1 = @"tableViewCell1";



@interface FirstTravelsController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong)UITableView *travelsTableView;

@property (nonatomic, strong) NSMutableArray *allArray;

@property (nonatomic, assign) BOOL isUpLoading;//标记上拉操作还是下拉操作,yes是上拉

@property (nonatomic, assign)NSInteger nextpage;//记录下一页

@end

@implementation FirstTravelsController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorPickerWithRGB(0xFF6EB4, 0x9C9C9C);
    self.view.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff, 0x9c9c9c);
    //数组初始化
    self.allArray = [NSMutableArray array];
   
    // 游记
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.travelsTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight - 66 - 49 - 44) style:UITableViewStylePlain];
//    self.travelsTableView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.travelsTableView];
    
    //消除分割线
    self.travelsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //成为代理人
    self.travelsTableView.delegate = self;
    self.travelsTableView.dataSource = self;
    
    //tableviewCell1注册
    [self.travelsTableView registerClass:[TravelsFirst_FirstTableViewCell class] forCellReuseIdentifier:tableViewCell1];
    
    
    self.isUpLoading = NO;
    //调用函数,获取数据
    [self getAFNetworkingData:self.nextpage];
    //2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    
}

//必须做的
//显示每个cell的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TravelsFirst_FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCell1 forIndexPath:indexPath];
    cell.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff, 0x9c9c9c);
//    cell.nameLabel.text = @"1111";
    cell.cellModel = [self.allArray objectAtIndex:indexPath.row];
   
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

#pragma mark--跳到游记详情页面的block第三步
    cell.travelsDetailsBlock = ^(ModuleFirst_TravelsTitleModel *model){
        
        TravelsDetailsController *MFTDVC = [[TravelsDetailsController alloc]init];
        UINavigationController *MFTDNaVC = [[UINavigationController alloc]initWithRootViewController:MFTDVC];
        MFTDVC.idd = model.idd;
        [self presentViewController:MFTDNaVC animated:YES completion:^{
            
            
        }];
        
    };
#pragma mark--跳到作者主页的block第三步
    cell.userHomepageBlock = ^(ModuleFirst_UserInformationModel *model){
      
        ModuleFirstUserHomepageViewController *MFUHVC = [[ModuleFirstUserHomepageViewController alloc]init];
        UINavigationController *MFUHNaVC = [[UINavigationController alloc]initWithRootViewController:MFUHVC];
        MFUHVC.userModel = model;
        [self presentViewController:MFUHNaVC animated:YES completion:^{
            
            
        }];
    };
    
//    cell.textLabel.text = @"1111";
    
    return cell;
}

//每个分区中cell的个数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.allArray.count;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(TravelsFirst_FirstTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    CATransform3D rotation;//3D旋转
    
    rotation = CATransform3DMakeTranslation(0 ,50 ,20);
    rotation = CATransform3DScale(rotation, 0.9, .9, 1);
    
    rotation.m34 = 1.0/ -600;
    
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    
    cell.layer.transform = rotation;
    
    [UIView beginAnimations:@"rotation" context:NULL];
    //旋转时间
    [UIView setAnimationDuration:0.9];
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    [UIView commitAnimations];
    
    
    
    
    
}



//******选做的******
//每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return TabelViewH / 2.5;
}


#pragma  mark --下拉刷新
- (void)addHeader{
    
    __block FirstTravelsController *root = self;
    
    self.travelsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        root.isUpLoading = NO;
        root.nextpage++;
        [root getAFNetworkingData:root.nextpage];
        [self.travelsTableView reloadData];
    }];
    
    
#pragma mark --自动刷新(--进入程序就下拉刷新)
    [self.travelsTableView.mj_header beginRefreshing];
    
}



#pragma mark -- 上拉加载更多
- (void)addFooter{
    
    __block FirstTravelsController *root = self;
    
    self.travelsTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        root.isUpLoading = YES;
        root.nextpage++;
        [root getAFNetworkingData:root.nextpage];
    }];
    
    [self.travelsTableView reloadData];
  }




//网络请求数据
- (void)getAFNetworkingData:(NSInteger)nextCursor{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //1) 创建一个管理者
    
//    2）在mainBundle中寻找我们刚才拖进项目中的https.cer, 并且将相关的数据读取出来
//    3）新建一个AFSecurityPolicy，并进行相应的配置
//    4）将这个AFSecurityPolicy 实例赋值给manager
    
   // allowInvalidCertificates 定义了客户端是否信任非法证书
    // validatesDomainName 是指是否校验在证书中的domain这一个字段。每个证书都会包含一个DomainName, 它可以是一个IP地址，一个域名或者一端带有通配符的域名。如*.google.com, www.google.com 都可以成为这个证书的DomainName。设置validatesDomainName=YES将严格地保证其安全性。
    
   
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    [manager.securityPolicy setValidatesDomainName:NO];
    //识别各种类型的网址
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    NSString *string = [NSString stringWithFormat:@"https://chanyouji.com/api/trips/featured.json?page=%ld",nextCursor] ;
 [manager GET:string parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
     
     
 } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
//     NSLog(@"%@", responseObject);
     
     // 结束网络监听
     [netWorkManager stopMonitoring];
     
     if (self.isUpLoading == NO) {
         
         //说明是下拉,就要清空数组中的数据
         [self.allArray removeAllObjects];
     }
     
     
     
     for (NSDictionary *dic in responseObject) {
         ModuleFirst_TravelsTitleModel *MF_TTModel = [[ModuleFirst_TravelsTitleModel alloc]init];
         [MF_TTModel setValuesForKeysWithDictionary:dic];
         [self.allArray addObject:MF_TTModel];
     }
     
     [self.travelsTableView.mj_footer endRefreshing];
     [self.travelsTableView.mj_header endRefreshing];
     
     [self.travelsTableView reloadData];

     
 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
     
     NSLog(@"error====%@",error);

     
 }]; 
    
    
}


@end
